﻿<%@ WebHandler Language="C#" Class="CreateOrder" %>

using System;
using System.Web;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using StarTech.DBUtility;
using System.Text;
using StarTech.Order.Order;
using StarTech.Order;

public class CreateOrder : IHttpHandler
{

    AdoHelper ado = AdoHelper.CreateHelper("DB_Instance");
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value))
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
            string flag = Common.NullToEmpty(context.Request["flag"]);

            string priceId = Common.NullToEmpty(context.Request["priceId"]);
            string orderId = Common.NullToEmpty(context.Request["orderId"]);

            string status = Common.NullToEmpty(context.Request["status"]);

            switch (flag.ToLower())
            {
                case "list":
                    context.Response.Write(GetOrderList(status));
                    break;
                case "add":
                    string[] priceIds = priceId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < priceIds.Length; i++)
                    {
                        SetPriceStatus(priceIds[i]);
                        AddOrder(priceIds[i]);
                    }
                    context.Response.Write('1');
                    break;
                case "delete":
                    context.Response.Write(DeleteOrder(orderId));
                    break;
                case "rehire":
                    string reJobStartTime = Common.NullToEmpty(context.Request["reJobStartTime"]);
                    int reJobDay = Common.NullToZero(context.Request["reJobDay"]);
                    string rePrice = Common.NullToEmpty(context.Request["rePrice"]);
                    context.Response.Write(ReHire(priceId, reJobStartTime, reJobDay, rePrice));
                    break;
            }
        }
        else
        {
            context.Response.Write("please login");
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private string ReHire(string priceId, string reJobStartTime, int reJobDay, string rePrice)
    {
        string strSql = "select * from T_Goods_MemberPrice where priceId=@priceId";
        SqlParameter[] p1 = { new SqlParameter("@priceId", priceId) };
        DataTable dt = ado.ExecuteSqlDataset(strSql, p1).Tables[0];
        if (dt.Rows.Count > 0)
        {
            if (Convert.ToDateTime(dt.Rows[0]["JobEndTime"]) > Convert.ToDateTime(reJobStartTime))
            {
                return "请完成原先合约后再续聘";
            }

            string newId = Guid.NewGuid().ToString();
            strSql = @"insert into T_Goods_MemberPrice(PriceId,JobType,GoodsId,MemberId,MemberMobile,MemberPrice,CreateTime,IsLast,IsEmployerSelect,IsMemberConfirm,isXP,JobStartTime,JobEndTime,JobDay) values(@PriceId,@JobType,@GoodsId,@MemberId,@MemberMobile,@MemberPrice,@CreateTime,1,1,0,1,@JobStartTime,@JobEndTime,@JobDay);";
            SqlParameter[] p2 = new SqlParameter[] {
                new SqlParameter("@PriceId",newId),
                new SqlParameter("@JobType",dt.Rows[0]["JobType"]),
                new SqlParameter("@GoodsId",dt.Rows[0]["GoodsId"]),
                new SqlParameter("@MemberId",dt.Rows[0]["MemberId"]),
                new SqlParameter("@MemberMobile",dt.Rows[0]["MemberMobile"]),
                new SqlParameter("@MemberPrice",rePrice),
                new SqlParameter("@CreateTime",DateTime.Now.ToString()),
                new SqlParameter("@JobStartTime",reJobStartTime),
                new SqlParameter("@JobEndTime",Convert.ToDateTime(reJobStartTime).AddDays(reJobDay).ToShortDateString()),
                new SqlParameter("@JobDay",reJobDay),
            };
            if (ado.ExecuteSqlNonQuery(strSql, p2) > 0)
            {
                AddOrder(newId);
                return "1";
            }
        }
        return "0";
    }

    private string DeleteOrder(string orderId)
    {
        SqlParameter[] p = { new SqlParameter("@orderId", orderId) };
        string priceId = ado.ExecuteSqlScalar("select priceId from T_Order_Info where orderId=@orderId", p).ToString();

        SqlParameter[] p1 = { new SqlParameter("@priceId", priceId) };
        ado.ExecuteSqlNonQuery("update T_Goods_MemberPrice set IsEmployerSelect='0',IsMemberConfirm='0' where priceId=@priceId", p1);

        string strSql = @"delete from T_Order_Info where orderId=@orderId; delete from T_Order_InfoDetail where orderId=@orderId;";
        SqlParameter[] p2 = { new SqlParameter("@orderId", orderId) };
        return ado.ExecuteSqlNonQuery(strSql, p2).ToString();
    }

    protected string GetOrderList(string status)
    {
        switch (status)
        {
            case "0":
                status = " and (c.JobStatus in ('竞价中','未发布') or a.IsPay='0')";
                break;
            case "1":
                status = " and c.JobStatus in ('进行中') and a.IsPay='1' and (IsComplete='0' or IsComplete is null)";
                break;
            case "2":
                status = " and a.IsComplete='1' ";
                break;
            default:
                status = " and (c.JobStatus in ('竞价中','未发布') or a.IsPay='0')";
                break;
        }

        string json = "";
        string strSql = @"select d.MemberPrice,d.MemberId as mid,a.OrderId,a.MemberName,f.TrueName,c.GoodsId,c.GoodsName,c.SalePrice,a.OrderAllMoney,c.JobType as OrderType,c.JobNeeds,c.JobStatus,c.JobAddress,ISNULL(d.JobStartTime,c.JobStartTime) as JobStartTime,ISNULL(d.JobEndTime,c.JobEndTime) as JobEndTime,ISNULL(d.JobDay,c.JobDay) as JobDay,d.IsMemberConfirm,a.IsPay,e.CategoryName,g.commentId,a.PriceId FROM T_Order_Info a
            left join T_Order_InfoDetail b on a.OrderId=b.OrderId
            right join T_Goods_Info c on b.GoodsId=c.GoodsId
            left join T_Goods_MemberPrice d on a.PriceId=d.PriceId
            left join T_Info_Category e on c.CategoryId=e.CategoryId
            left join T_Member_Info f on d.MemberId=f.MemberId
            left join T_Order_Comment g on a.OrderId=g.OrderId and g.createMemberId=@memberId
            where (c.ProviderInfo=@memberId) " + status+" order by ordertime desc";

        SqlParameter[] parameters = { new SqlParameter("@memberId", memberId) };

        DataTable dt = ado.ExecuteSqlDataset(strSql, parameters).Tables[0];
        json = JSONHelper.GetJSON(dt);
        return json;
    }

    protected string SetPriceStatus(string priceId)
    {
        string strSql = "update T_Goods_MemberPrice set IsEmployerSelect='1', EmployerSelectTime=getdate() where priceId=@priceId";
        SqlParameter[] parameters =
        {
            new SqlParameter("@priceId", priceId)
        };
        string result = ado.ExecuteSqlNonQuery(strSql, parameters).ToString();

        strSql = "select top 1 jobType from T_Goods_MemberPrice where priceId=@priceId";
        SqlParameter[] p2 =
        {
            new SqlParameter("@priceId", priceId)
        };
        string jobType = ado.ExecuteSqlScalar(strSql, p2).ToString();

        string mId = Common.GetWorkerIdByPriceId(priceId);
        string GoodsName = Common.GetGoodsNameByPriceId(priceId);
        string TrueName = Common.GetBossNameByPriceId(priceId);
        Common.AddLogMsg(mId, "雇主接受报价", "【" + GoodsName + "】任务的雇主 " + TrueName + " 已接受您的报价", "MyAcceptTask" + (jobType.Equals("DG") ? "People" : "") + "List.html", 0);

        return result;
    }


    /// <summary>
    /// 订单主表T_Order_Info
    /// </summary>
    protected string AddOrder(string PriceId)
    {
        //判断重复下单
        if (ado.ExecuteSqlScalar("select orderId from T_Order_Info where priceId='" + PriceId + "'") != null)
        {
            return "";
        }
        
        //读取报价表和其他信息
        //报价表
        SqlParameter[] parameters =
        {
            new SqlParameter("@priceId", PriceId)
        };
        DataTable dtPrice = ado.ExecuteSqlDataset("select * from T_Goods_MemberPrice where PriceId=@priceId", parameters).Tables[0];
        if (dtPrice.Rows.Count == 0) { return ""; }
        string MemberId = dtPrice.Rows[0]["MemberId"].ToString();       //（重要）雇员编号
        string GoodsId = dtPrice.Rows[0]["GoodsId"].ToString();         //（重要）工程信息编号
        decimal OrderAllMoney = decimal.Parse(dtPrice.Rows[0]["MemberPrice"].ToString());     //（重要）订单价格
        if (dtPrice.Rows[0]["JobType"].ToString() == "DG") { OrderAllMoney = decimal.Parse(dtPrice.Rows[0]["MemberPrice"].ToString()) * int.Parse(dtPrice.Rows[0]["JobDay"].ToString()); }
        string Tel = dtPrice.Rows[0]["MemberMobile"].ToString();

        //会员表
        DataTable dtMember = ado.ExecuteSqlDataset("select * from T_Member_Info where MemberId='" + MemberId + "'").Tables[0];
        if (dtMember.Rows.Count == 0) { return ""; }
        string MemberName = dtMember.Rows[0]["MemberName"].ToString();
        string TrueName = dtMember.Rows[0]["TrueName"].ToString();
        string AddressCode = dtMember.Rows[0]["AddressCode"].ToString();
        string AddressDetail = dtMember.Rows[0]["AddressDetail"].ToString();
        string PostCode = dtMember.Rows[0]["PostCode"].ToString();

        //工程需求信息表
        DataTable dtGoods = ado.ExecuteSqlDataset("select * from T_Goods_Info where GoodsId='" + GoodsId + "'").Tables[0];
        if (dtGoods.Rows.Count == 0) { return ""; }
        string SellerId = dtGoods.Rows[0]["ProviderInfo"].ToString();    //（重要）雇主编号
        string JobType = dtGoods.Rows[0]["JobType"].ToString();          //（重要）订单类型，和工作类型关联：全包（QB）、钟点工（DG）


        //订单主表（订单主信息，包括人员信息和价格信息等）
        ModOrder mod = new ModOrder();

        //订单基本信息
        mod.OrderId = DateTime.Now.ToString("yyyyMMddHHmmss") + MemberId + new Random().Next(1000, 9999).ToString();
        mod.OrderType = JobType;                                         //（重要）订单类型，和工作类型关联：全包（QB）、钟点工（DG）
        mod.OrderTime = DateTime.Now;
        mod.SendMethod = "off";
        mod.PayMethod = "在线支付";


        //雇员信息
        mod.MemberId = MemberId;                                        //（重要）雇员编号
        mod.MemberName = MemberName;
        mod.MemberOrderRemarks = "";                                    //订单备注（备用）
        mod.ReceivePerson = TrueName;
        mod.ReceiveAddressCode = AddressCode;
        mod.ReceiveAddressDetail = AddressDetail;
        mod.Tel = Tel;
        mod.PostCode = PostCode;

        //雇主信息
        mod.SellerId = SellerId;                                        //（重要）雇主编号

        //价格信息
        mod.OrderAllMoney = OrderAllMoney;                              //（重要）订单价格
        mod.GoodsAllMoney = OrderAllMoney;
        mod.OrderAllWeight = 0;
        mod.OrderAllWeight = 0;

        //支付信息
        mod.IsPay = 0;                                                  //（重要）是否支付
        mod.PayInterfaceCode = "";                                      //第三方支付接口提交的编号，查账用
        mod.PayMethod = "";                                             //支付方式（支付宝ZFB，微信WX等）
        mod.PayTime = DateTime.Now;                                     //支付时间

        mod.priceId = PriceId;

        //创建订单
        if (new BllOrder().Add(mod) > 0)
        {
            //明细信息
            AddOrderDetail(mod.OrderId, mod.OrderType, GoodsId);
        }

        return mod.OrderId;
    }


    /// <summary>
    /// 订单明细T_Order_InfoDetail
    /// </summary>
    protected int AddOrderDetail(string OrderId, string OrderType, string GoodsId)
    {
        DataTable dt = ado.ExecuteSqlDataset("select * from T_Goods_Info where GoodsId='" + GoodsId + "'").Tables[0];
        BllOrderDetail bllDetail = new BllOrderDetail();
        int i = 0;
        foreach (DataRow row in dt.Rows)
        {
            ModOrderDetail mod = new ModOrderDetail();
            mod.OrderId = OrderId;
            mod.OrderType = OrderType;
            mod.GoodsId = row["GoodsId"].ToString();
            mod.GoodsName = row["GoodsName"].ToString();
            mod.GoodsCode = row["GoodsCode"].ToString();
            mod.GoodsFormate = "";
            mod.Price = decimal.Parse(row["SalePrice"].ToString());
            mod.GoodsPic = row["GoodsSmallPic"].ToString();
            mod.ProviderInfo = row["ProviderInfo"].ToString();
            mod.DataFrom = row["DataFrom"].ToString();
            mod.Quantity = 1;
            mod.AllMoney = mod.Price * mod.Quantity;
            mod.AllWeight = mod.OneWeight * mod.Quantity;
            i += bllDetail.Add(mod);
        }
        return i;
    }


}